package awd.bj.jls.webs.controller;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

import awd.bj.jls.model.PhotosModel;
import awd.bj.jls.model.XyrModel;
import awd.bj.jls.webs.api.JlsServersApi;
import awd.bj.jls.webs.api.model.User;
import awd.bj.jls.webs.utils.DefaultQueryParam;
import awd.bj.jls.webs.utils.PagerResult;
import awd.bj.jls.webs.utils.QueryParam;
import awd.bj.jls.webs.utils.ResponseMessage;
import awd.bj.jls.webs.utils.Result;
import awd.bj.jls.webs.utils.ResultUtils;
import awd.bj.jls.webs.utils.TermType;

@Controller
@RequestMapping("/xyr")
@RefreshScope
public class XyrAction extends BaseAction{
	@Autowired
    private JlsServersApi jlsServersApi;
	
	 /**
     * 数据列表查询嫌疑人表
     * @param request
     * @param params 所有请求的参数集合
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request,Map<String,Object> params) {
        QueryParam param = DefaultQueryParam.requestUtil(request);
        System.err.println(JSON.toJSON(param));
        ResponseMessage<PagerResult<XyrModel>> list = jlsServersApi.xyrQueryForPage(param);
        Map<String, Object> result = Maps.newHashMap();
        result.put("total", list.getResult().getTotal());
        result.put("rows", list.getResult().getData());
        return result;
    }

    
    /**
     * 	嫌疑人快速入所的保存操作
     * @param multiRequest
     * @param model
     * @return
     */
    @RequestMapping("/ksrsSave")
    @ResponseBody
    public Result<?> ksrsSave(MultipartHttpServletRequest multiRequest, @ModelAttribute XyrModel model){
        User users = getCurrentUser();
        try {
            //model.setState("R2");
            model.setJsbh(users.getJsbh());
            model.setCreatetime(new Date());
            model.setCreator(users.getUsername());
            model.setState("R2");
            model.setCzzt("01");
            System.err.println(JSON.toJSONString(model));
            //先调用嫌疑人的快速入所保存接口，返回一个人员编号，再用这个rybh 保存该人的图片
            ResponseMessage<String> res = jlsServersApi.saveAsKsrs(model);
           // ResponseMessage<String> res = ResponseMessage.ok();
            String photostype="";
            System.err.println("res==="+JSON.toJSONString(res));
            if (res.getStatus() == 200) {	//200正常在执行照片保存的接口

                Iterator<String> iterable = multiRequest.getFileNames();
                System.err.println("iterable----"+JSON.toJSONString(iterable.hasNext()));
                while (iterable.hasNext()) {
                	System.err.println("-----迭代中------");
                    //Map<String, Object> reMap = Maps.newHashMap();
                    //取出单个文件
                    MultipartFile file = multiRequest.getFile(iterable.next());
                    String fileName = file.getName();
                    photostype+=fileName+',';
                    System.err.println(fileName);
    				if ("leftPhoto".equals(fileName)) {	//实际前台传来的左侧照片
    					jlsServersApi.uploadLeftPhoto(res.getResult(),users.getUsername(),users.getJsbh(),file);
    				}else if("centerPhoto".equals(fileName)){	//实际前台传来的正面照
    					jlsServersApi.uploadCenterPhoto(res.getResult(),users.getUsername(),users.getJsbh(),file);
    				}else if ("rightPhoto".equals(fileName)) {
    					jlsServersApi.uploadRightPhoto(res.getResult(),users.getUsername(),users.getJsbh(),file);
    				}
    				/*if (StringUtils.isNullOrEmpty(file.getOriginalFilename())) {
    					jlsServersApi.uploadPhoto(res.getResult(),file);
					}*/
                }
                //如果没传照片新建空数据
                PhotosModel photosModel = new PhotosModel();
                photosModel.setJsbh(users.getJsbh());
            	photosModel.setRybh(res.getResult());
            	photosModel.setYwzp("0");
            	photosModel.setState("R2");
            	photosModel.setCreatetime(new Date());
            	photosModel.setCreator(users.getUsername());
                if(!photostype.contains("leftPhoto")) {
                	photosModel.setType("2");
                	jlsServersApi.photosSave(photosModel);
                }
                if(!photostype.contains("centerPhoto")) {
                	photosModel.setType("1");
                	jlsServersApi.photosSave(photosModel);
                }
                if(!photostype.contains("rightPhoto")) {
                	photosModel.setJsbh(users.getJsbh());
                	photosModel.setType("3");
                	jlsServersApi.photosSave(photosModel);
                }
                System.err.println(photostype);
                //不管照片存没存，我们都返回
                return ResultUtils.success("成功");
//                return ResultUtils.success(res.getResult());
			}
            //不用说 这里就是返回失败结果
            return ResultUtils.error(Result.ERR_SAVE, "保存失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(Result.ERR_SAVE, "保存失败");
        }
    }
    
    /**
     * 	嫌疑人简要登记的保存操作
     * @param model
     * @return
     */
    @RequestMapping("/xyrSave")
    @ResponseBody
    public Result<?> save(@ModelAttribute XyrModel model){
        User users = getCurrentUser();
        try {
            model.setState("R2");
            model.setJsbh(users.getJsbh());
            model.setCreatetime(new Date());
            model.setCreator(users.getUsername());
            model.setCzzt("01");
            System.err.println("=======================何磊=========================");
            System.err.println("======================保存数据1======================");
            System.err.println(JSON.toJSONString(model));
            System.err.println("===========================何磊=====================");

            return ResultUtils.success(jlsServersApi.saveAsXyr(model));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(Result.ERR_SAVE, "保存失败");
        }
    }
    
    
    /**
     * 	嫌疑人另行处理
     * @param model
     * @return
     */
    @RequestMapping("/xyrSaveAsLycl")
    @ResponseBody
    public Result<?> saveAslxcl(HttpServletRequest request,@ModelAttribute XyrModel model){
        User users = getCurrentUser();
        try {
        	System.err.println("model---"+model.getByjswsh()+"---"+model.getJsrq());
        	String taskid = request.getParameter("taskid");
        	model.setJsbh(users.getJsbh());
        	model.setTaskid(taskid);
            return ResultUtils.success(jlsServersApi.saveAsLxcl(model));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(Result.ERR_SAVE, "保存失败");
        }
    }
    
}
